package com.hengpeng.itfints.controller.member;

import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.constants.SystemConfigConstants;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.BindCardRequest;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.message.partner.ModifyRequest;
import com.hengpeng.itfinbase.message.partner.NotifyRequestMsg;
import com.hengpeng.itfinbase.message.partner.NotifyResponseMsg;
import com.hengpeng.itfinbase.message.partner.OpenRequestMsg;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.itfints.constants.PartnerUtil;
import com.hengpeng.itfints.constants.SystemConfigUtil;
import com.hengpeng.itfints.controller.BaseController;
import com.hengpeng.itfints.tools.JsonUtils;

@Controller
public class UserInfoController extends BaseController
{
	protected Log logger = LogFactory.getLog(this.getClass());

	/**
	 * <pre>
	 * 汇付开户
	 * </pre>
	 * @param request
	 * @param memberId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/member_operate/openRequest", method = RequestMethod.POST)
	@ResponseBody
	public ServiceResult<ResponseMessage> open(HttpServletRequest request, String memberId,String cardNumber,String realname) throws Exception
	{
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		OpenRequestMsg reqMsg = new OpenRequestMsg();
		UserInfo m = getSessionMember(request).getUser();
		reqMsg.setUserId(String.valueOf(m.getId()));
		reqMsg.setCardNumber(cardNumber);
		reqMsg.setEmail(m.getEmail().trim());
		reqMsg.setMobile(m.getMobile().trim());
		reqMsg.setRealName(realname);
		reqMsg.setMerPriv(String.valueOf(m.getId()));
		reqMsg.setPartnerTransType(PartnerTransType.UserRegister);
		reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
		ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
		result.setReturnValue(response);
		return result;
	}

	/**
	 * <pre>
	 * 页面返回
	 * </pre>
	 * @param map
	 * @param request
	 * @param response
	 * @param providerId
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/pgNotify")
	public String pgNotify(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		NotifyRequestMsg requestMessage = new NotifyRequestMsg();
		requestMessage.setIsBgNotify(false);
		requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
		StringBuffer parameterStr = new StringBuffer();
		Map<String, String> parameterMap = new HashMap<String, String>();
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements())
		{
			String paramName = params.nextElement();
			parameterStr.append("&" + paramName + "=" + URLDecoder.decode(request.getParameter(paramName), "utf-8"));
			parameterMap.put(paramName, URLDecoder.decode(request.getParameter(paramName), "utf-8"));
		}
		if (parameterStr.length() > 0)
		{
			parameterStr.delete(0, 1);
		}
		requestMessage.setParamString(JsonUtils.createGson().create().toJson(parameterMap));
		requestMessage.setParameter(parameterMap);
		logger.info("第三方页面返回参数{" + parameterStr.toString() + "}");
		NotifyResponseMsg port_result = (NotifyResponseMsg) serviceFactory.getProtFactory().remoteTrans(requestMessage);
		refreshSessionMember(request);
		map.put("resultObj", port_result);
		return "/page/common_page_result.jsp";
	}

	/**
	 * <pre>
	 * 服务端响应
	 * </pre>
	 * @param map
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/bgNotify")
	public void bgNotify(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		NotifyRequestMsg requestMessage = new NotifyRequestMsg();
		requestMessage.setIsBgNotify(true);
		requestMessage.setTransType(TransCodeConstants.PartnerTransCode.NOTIFY);
		Map<String, String> parameter = new HashMap<String, String>();
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements())
		{
			String paramName = params.nextElement();
			parameter.put(paramName, request.getParameter(paramName));
		}
		requestMessage.setParamString(JsonUtils.createGson().create().toJson(parameter));
		requestMessage.setParameter(parameter);
		logger.info("第三方后台通知参数{" + parameter.toString() + "}");
		NotifyResponseMsg port_result = (NotifyResponseMsg) serviceFactory.getProtFactory().remoteTrans(requestMessage);
		refreshSessionMember(request);
		map.put("param", port_result.getReturnNotifyParamValue());
		if (port_result.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC))
		{
			response.getWriter().print(port_result.getReturnNotifyParamValue());
		}
	}

	/**
	 * <pre>
	 * 提现
	 * </pre>
	 * @param request
	 * @param money
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/member_operate/draw", method = RequestMethod.POST)
	@ResponseBody
	public ServiceResult<ResponseMessage> draw(HttpServletRequest request, String money, Long bankCardId)
			throws Exception
	{
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		CashRequestMsg reqMsg = new CashRequestMsg();
		UserInfo m = getSessionMember(request).getUser();
		reqMsg.setUserId(m.getId());
		reqMsg.setTransAmt(money);
		reqMsg.setPartnerTransType(PartnerTransType.Cash);
		reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
		if (!PartnerUtil.isTrustPattern()){
			reqMsg.setBankCardId(bankCardId);
			reqMsg.setProviderId(SystemConfigUtil.getConfigValue(SystemConfigConstants.DRAW_PROVIDERID));
		}
		ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
		result.setReturnValue(response);
		if (!validateObjectsNullOrEmpty(response))
		{
			result.setMessage(response.getRespDesc());
			result.setCode(response.getRespCode());
			if (response.getRespCode().equalsIgnoreCase(RespCodeConstants.CommonCode.TRANS_SUC))
			{
				result.setIsSuccess(true);
			}
			else
			{
				result.setIsSuccess(false);

			}
		}
		else
		{
			result.setMessage("请求出错，请重试！");
			result.setIsSuccess(false);
			result.setCode(RespCodeConstants.CommonCode.TRANS_FAIL);
			logger.info("充值请求出错，返回null");
		}
		result.setReturnObject(PartnerUtil.isTrustPattern());
		refreshSessionMember(request);
		return result;
	}

	/**
	 * <pre>
	 * 绑卡
	 * </pre>
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/member_operate/bindCard", method = RequestMethod.POST)
	@ResponseBody
	public ServiceResult<ResponseMessage> bindCard(HttpServletRequest request) throws Exception
	{
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		ResponseMessage response = new ResponseMessage();
		if (!PartnerUtil.isTrustPattern())
		{
			response.setOrderFormContent("/memberCenter/addUserBankCard.htm");
			result.setReturnValue(response);
		}
		else
		{
			BindCardRequest reqMsg = new BindCardRequest();
			UserInfo m = getSessionMember(request).getUser();
			reqMsg.setUserId(m.getId());
			reqMsg.setUsrCustId(m.getTrustAccountId());
			reqMsg.setPartnerTransType(PartnerTransType.UserBindCard);
			reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
			response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
			result.setReturnValue(response);
		}
		return result;
	}

	/**
	 * 用户到第三方修改资料
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/member_operate/modifyToPartner", method = RequestMethod.POST)
	@ResponseBody
	public ServiceResult<ResponseMessage> modifyToPartner(HttpServletRequest request) throws Exception
	{
		ServiceResult<ResponseMessage> result = new ServiceResult<ResponseMessage>();
		ModifyRequest reqMsg = new ModifyRequest();
		UserInfo m = getSessionMember(request).getUser();
		reqMsg.setPartnerTransType(PartnerTransType.AcctModify);
		reqMsg.setUsrCustId(m.getTrustAccountId());
		reqMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
		ResponseMessage response = (ResponseMessage) serviceFactory.getProtFactory().remoteTrans(reqMsg);
		result.setReturnValue(response);
		return result;
	}
}
